import axios, {
  AxiosResponse,
  InternalAxiosRequestConfig,
  AxiosError,
  Axios,
  AxiosRequestConfig,
} from "axios";
import { ResultEnum } from "@/enums/httpEnum";

export interface MyResponseType<T> {
    vcode: any;
    code: number;
    data: T;
    msg?: string;
    holdAll?: T;
}

export interface MyRequestInstance extends Axios {
  <T = any>(config: AxiosRequestConfig): Promise<MyResponseType<T>>;
}

const axiosInstance = axios.create({
    baseURL: __DEV__?'http://192.168.43.91:5000/' : 'http://localhost:5000/', // 使用环境变量配置基础URL
    timeout: ResultEnum.TIMEOUT, // 设置请求超时时间
}) as unknown as MyRequestInstance;

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加取消请求功能
    const cancelTokenSource = axios.CancelToken.source();
    config.cancelToken = cancelTokenSource.token; // 绑定取消令牌
    config.meta = { cancelTokenSource }; // 把取消令牌保存在请求的 meta 中，以便之后使用

    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (res: AxiosResponse) => {
    const { code } = res.data as { code: number };
    if (code === undefined || code === null) {
      return Promise.resolve(res.data);
    }
    if (code === 200) {
      // 假设200表示成功
      return Promise.resolve(res.data);
    }
    return Promise.reject(res.data); // 统一处理错误
  },
  async (error) => {
    const originalRequest = error.config;
    const MAX_RETRIES = 3; // 设置最大重试次数

    if (error.response) {
      switch (error.response.status) {
        case 400:
          console.error("Bad Request - 400");
          break;
        case 401:
          console.error("Unauthorized - 401");
          break;
        case 500:
          console.error("Internal Server Error - 500");
          break;
        default:
          console.error(`Error - ${error.response.status}`);
      }
    }

    // 重试机制
    if (originalRequest._retryCount === undefined) {
      originalRequest._retryCount = 0;
    }
    if (
      error.response &&
      error.response.status === 500 &&
      originalRequest._retryCount < MAX_RETRIES
    ) {
      originalRequest._retryCount += 1; // 增加重试次数
      originalRequest._retry = true; // 标记为已重试请求
      try {
        return await axiosInstance(originalRequest); // 重试请求
      } catch (retryError) {
        console.error("Retry Error:", retryError);
      }
    }

    return Promise.reject(error);
  },
);

// 取消请求的函数
export const cancelRequest = (config: AxiosRequestConfig) => {
  if (config.meta && config.meta.cancelTokenSource) {
    config.meta.cancelTokenSource.cancel("Request was canceled");
  }
};

// 取消请求的拦截器
export const setupCancelInterceptor = (axiosInstance: Axios) => {
  axiosInstance.interceptors.response.use(
    (response) => response,
    (error) => {
      if (axios.isCancel(error)) {
        console.log("Request canceled", error.message);
      }
      return Promise.reject(error);
    },
  );
};

setupCancelInterceptor(axiosInstance); // 绑定取消请求拦截器

export default axiosInstance;
